package com.ruoyi.kis.controller;

import cn.hutool.http.HttpException;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult_KIS;
import com.ruoyi.kis.Vars.Constants;
import com.ruoyi.kis.domain.MaterialRequisiteF;
import com.ruoyi.kis.service.IKisService;
import com.ruoyi.kis.util.HttpSendWmsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author: zhanglm
 * @CreateDate: 2025-03-11 10:54
 * @FullNameClass: com.ruoyi.kis.controller.KisSctldController
 * @Description: 生产退料单
 */
@RestController
@RequestMapping("/kissctld")
@Component("kissctld")
@Api("kis接口")
public class KisSctldController extends BaseController {


    @Autowired
    private IKisService kisService;

    private static final Logger LOGGER = LoggerFactory.getLogger(KisSctldController.class);


    /**
     * 生产退料单
     *在KIS的ERP中生产退料单：在ERP中做负生产领料单就可以
     * ERP > WMS
     * @return json
     */
    @ApiOperation("生产退料单")
    @RequestMapping("/sctld")
    public AjaxResult_KIS tuiliaodan(){
        MaterialRequisiteF sctldF = kisService.querySctldF();
        String s  = "";
        if (sctldF != null  ){


                s = JSONUtil.parse(sctldF).toString();
                try {
//                    String msg = HttpUtil.post(Constants.SCTLD_URL,s);
                    String msg = HttpSendWmsUtil.sendWms(Constants.SCTLD_URL,s);
                    LOGGER.info("生产退料单 ERP >> WMS:"+msg);
                    JSONObject entries = JSONUtil.parseObj(msg);
                    String msgcode = entries.get("msgcode").toString();
                    String kisFlag;
                    if (msgcode.equals(Constants.ZHIKU.MSGCODE_SUCCESS)){
                        kisFlag = Constants.ZHIKU.KISFLAG_SUCCESS;
                    }else {
                        kisFlag = Constants.ZHIKU.KISFLAG_FAILURE;
                    }
                    int countUpdate = kisService.updateKisICStockBillFlag(sctldF.getFInterID(),kisFlag);
                    LOGGER.info("生产退料单 ERP >> WMS:单据:{},kisFlag值：{}，更新：{}条,反馈：{}",sctldF.getFBillNo(),kisFlag,countUpdate,msg);
                }catch (HttpException e){
                    LOGGER.error("生产退料单失败" + e.getMessage());
                }

        }
        return AjaxResult_KIS.success("OK","");
    }
}
